iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 28
0
Mobile Development

Android 到底能幹嘛 ?系列 第 28

[Day28] Room | 坑要來了

  • 分享至 

  • xImage
  •  

首先我們建立的UserData.kt
就是我們資料庫中每一筆資料的欄位

@Entity
data class UserData(
    @PrimaryKey(autoGenerate = true) var uid: Int,
    @ColumnInfo(name = "app_name") var name: String?,
    @ColumnInfo(name = "account") var account: String?,
    @ColumnInfo(name = "password") var password: String?
)

PrimaryKey 代表主鍵
剩下都是其它欄位

以及新增UserDao.kt

import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query

@Dao
interface UserDao {
    @Query("SELECT * FROM users")
    fun getAll(): List<UserData>

    @Query("SELECT * FROM users WHERE uid IN (:userIds)")
    fun loadAllByIds(userIds: IntArray): List<UserData>

    @Query("SELECT * FROM users WHERE app_name LIKE :first AND " +
            "account LIKE :last LIMIT 1")
    fun findByName(first: String, last: String): UserData

    @Insert
    fun insertAll(vararg users: UserData)

    @Delete
    fun delete(user: UserData)
}

此interface主要是操作SQL語法
還有許多資料庫CRUD方法都寫在這

新增Appdatabase.kt

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase


@Database(entities = [(UserData::class)], version = 1, exportSchema = false)
abstract class Appdatabase : RoomDatabase() {

    companion object {
        const val DATABASE_NAME = "123.db"
        @Volatile private var instance: Appdatabase? = null
        private val LOCK = Any()

        operator fun invoke(context: Context)= instance ?: synchronized(LOCK){
            instance ?: buildDatabase(context).also { instance = it}
        }

        private fun buildDatabase(context: Context) = Room.databaseBuilder(context,
            Appdatabase::class.java, DATABASE_NAME).build()
    }

    abstract fun getNotesDao(): UserDao
}

上一篇
[Day27] Room | 官方目前推薦不使用Sqlite
下一篇
[Day29] Room創出來就好嗎?
系列文
Android 到底能幹嘛 ?30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言